package com.mallsystem.userservice.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mallsystem.common.bean.Collect;
import com.mallsystem.common.exception.AllException;
import com.mallsystem.common.service.CollectService;
import com.mallsystem.common.service.GoodsService;
import com.mallsystem.userservice.mapper.CollectMapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CollectServiceImpl implements CollectService {
    @Autowired
    private CollectMapper collectMapper;
    @DubboReference
    private GoodsService goodsService;
    //注意：一个商品只能被一个用户收藏一次
    @Override
    public boolean insert(Collect collect) throws AllException {
        //根据商品id和用户id查询
        if (collectMapper.selectByGoodsIdAndUserId(collect.getGoodsId(),collect.getUserId()) != null) {
            throw new AllException("该商品已经被收藏");
        }
        //添加收藏
        return collectMapper.insert(collect) == 1;
    }

    @Override
    public boolean delete(Integer id, Integer userId) throws AllException {
        //判断这个收藏是否存在
        Collect collect = collectMapper.selectById(id);
        if(collect == null){
            throw new AllException("该收藏不存在,无法取消收藏");
        }
        //判断这个收藏是否属于当前用户
        if(!collect.getUserId().equals(userId)){
            throw new AllException("该收藏属于其他用户,无法取消收藏");
        }
        //删除 - 取消收藏
        return collectMapper.delete(id) == 1;
    }

    @Override
    public Collect selectByGoodsIdAndUserId(Integer goodsId, Integer userId) {
        Collect collect = collectMapper.selectByGoodsIdAndUserId(goodsId, userId);
        collect.setGoods(goodsService.selectById1(collect.getGoodsId()));
        return collect;
    }

    @Override
    public PageInfo<Collect> selectByPage(Integer pageNum, Integer pageSize,Integer userId) {
        //设置分页参数
        PageHelper.startPage(pageNum,pageSize);
        //查询
        List<Collect> collects = collectMapper.selectByUserId(userId);
        for (Collect collect : collects) {
            collect.setGoods(goodsService.selectById1(collect.getGoodsId()));
        }
        //创建分页信息
        PageInfo<Collect> pageInfo = new PageInfo<>(collects);
        return pageInfo;
    }
}
